/* eslint-disable @typescript-eslint/no-explicit-any */
import { handlersItf, EventItf } from './types/global'

export class EventEmitter {
	handlers: handlersItf
	constructor(){
		this.handlers = {}
	}
	on(type: string, handler: <T extends EventItf>(event: T) => void){
		if(typeof this.handlers[type] === 'undefined'){
			this.handlers[type] = []
		}
		this.handlers[type].push(handler)
	}
	emit<T extends EventItf>(type: string,event: T){
		if(!event.target){
			event.target = this
		}
		if(this.handlers[type] instanceof Array){
			const handlers = this.handlers[type]
			handlers.forEach((handler)=>{
				handler(event)
			})
		}
	}
	off(type: string,handler: <T extends EventItf>(event: T) => void){
		if(this.handlers[type] instanceof Array){
			const handlers = this.handlers[type]
			let index = 0
			for(let i = 0,len = handlers.length; i < len; i++){
				if(handlers[i] === handler){
					index = i
					break
				}
			}
			handlers.splice(index,1)
		}
	}
}

export default Event